#!/bin/bash

# 查找并关闭 npm run prod 进程
echo "正在查找 metro-crawler 进程..."

# 查找包含 "npm run prod" 的进程
NPM_PIDS=$(ps aux | grep -E "npm run prod|metro-crawler" | grep -v grep | awk '{print $2}')

if [ -z "$NPM_PIDS" ]; then
    echo "未找到运行中的 metro-crawler 进程"
else
    echo "找到以下进程："
    ps aux | grep -E "npm run prod|metro-crawler" | grep -v grep
    
    echo ""
    echo "正在关闭进程..."
    for pid in $NPM_PIDS; do
        echo "关闭进程 PID: $pid"
        kill -TERM $pid 2>/dev/null
        if [ $? -eq 0 ]; then
            echo "已发送终止信号到进程 $pid"
        else
            echo "无法终止进程 $pid (可能已经停止)"
        fi
    done
    
    # 等待几秒，如果进程还在运行，强制杀死
    sleep 3
    for pid in $NPM_PIDS; do
        if kill -0 $pid 2>/dev/null; then
            echo "强制关闭进程 PID: $pid"
            kill -9 $pid 2>/dev/null
        fi
    done
fi

# 查找并关闭日志轮转进程（包含 check_and_rotate_log 函数的进程）
ROTATE_PIDS=$(ps aux | grep "check_and_rotate_log" | grep -v grep | awk '{print $2}')

if [ ! -z "$ROTATE_PIDS" ]; then
    echo ""
    echo "正在关闭日志轮转进程..."
    for pid in $ROTATE_PIDS; do
        kill -TERM $pid 2>/dev/null
        echo "已关闭日志轮转进程 PID: $pid"
    done
fi

echo ""
echo "metro-crawler 已停止"

# 显示最新的日志文件位置
LOG_DIR="/data/metro-crawler/logs"
if [ -d "$LOG_DIR" ]; then
    LATEST_LOG=$(ls -t $LOG_DIR/metro-crawler-*.log 2>/dev/null | head -1)
    if [ ! -z "$LATEST_LOG" ]; then
        echo "最新日志文件: $LATEST_LOG"
    fi
fi 